package com.jieli.stream.dv.running2.ui.fragment;


import android.content.ComponentName;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jieli.stream.dv.running2.R;
import com.jieli.stream.dv.running2.ui.activity.MainActivity;
import com.jieli.stream.dv.running2.ui.base.BaseFragment;
import com.jieli.stream.dv.running2.util.ClientManager;
import com.jieli.stream.dv.running2.util.Dbug;
import com.jieli.stream.dv.running2.util.IConstant;
import com.jieli.stream.dv.running2.util.IWifiDirectListener;
import com.jieli.stream.dv.running2.util.PreferencesHelper;
import com.jieli.stream.dv.running2.util.ToastUtil;
import com.jieli.stream.dv.running2.util.WifiHelper;
import com.jieli.stream.dv.running2.util.WifiP2pHelper;

import java.net.InetAddress;
import java.util.List;

public class DeviceListFragment extends BaseFragment implements View.OnClickListener {
    private static String tag = DeviceListFragment.class.getSimpleName();

    public DeviceListFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_device_list, container, false);
        ImageView mSwitchMode = (ImageView) view.findViewById(R.id.device_list_switch_search_mode);

        mSwitchMode.setOnClickListener(this);
        TextView tvEnterWiFiSettings = (TextView) view.findViewById(R.id.go_to_wifi);
        tvEnterWiFiSettings.setOnClickListener(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity() == null) return;
        Bundle bundle = getArguments();
        if (bundle != null) {
            int mode = bundle.getInt(KEY_SEARCH_MODE, AP_SEARCH_MODE);
            mApplication.setSearchMode(mode);
            Dbug.e(tag, "onActivityCreated: mode=" + mode);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Dbug.e(tag, "Current mode=" +mApplication.getSearchMode());
        if(IConstant.isWifiP2pEnable && mApplication.getSearchMode() == IConstant.AP_SEARCH_MODE){
            WifiP2pHelper.getInstance(mApplication).registerBroadcastReceiver(mIWifiDirectListener);
            Dbug.i(tag, "registerBroadcastReceiver");
            WifiP2pHelper.getInstance(mApplication).requestPeerList();
            Dbug.i(tag, "requestPeerList");
            WifiP2pHelper.getInstance(mApplication).startDiscoverPeers(new WifiP2pManager.ActionListener() {
                @Override
                public void onSuccess() {
                    Dbug.i(tag, "start discovery wifi direct list");
                }

                @Override
                public void onFailure(int i) {
                    Dbug.e(tag, "start discovery error, code : " +i);
                }
            });
        }
        if (WifiHelper.getInstance(getContext()).isWifiClosed()) {
            ToastUtil.showToastShort(getString(R.string.tip_open_wifi));
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(IConstant.isWifiP2pEnable){
            WifiP2pHelper.getInstance(mApplication).stopDiscoverPeers(null);
            WifiP2pHelper.getInstance(getContext()).unregisterBroadcastReceiver(mIWifiDirectListener);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        if (view != null && getActivity() != null) {
            switch (view.getId()) {
                case R.id.device_list_switch_search_mode:
                    toQrCodeFragment();
                    break;
                case R.id.go_to_wifi:
                    enterWiFiSettings();
                    break;
            }
        }
    }

    private void enterLiveVideo() {
        //Dbug.w(tag, "It has connected.");
        BaseFragment fragment = (BaseFragment) getActivity().getSupportFragmentManager().findFragmentByTag(VideoFragment.class.getSimpleName());
        if (fragment == null) fragment = new VideoFragment();

        ((MainActivity)getActivity()).changeFragment(R.id.container, fragment, fragment.getClass().getSimpleName());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private void toQrCodeFragment() {
        Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.container);
        if (!(fragment instanceof QRCodeFragment)) {
            fragment = new QRCodeFragment();
        }
        ((MainActivity)getActivity()).changeFragment(R.id.container, fragment, fragment.getClass().getSimpleName());
    }

    private IWifiDirectListener mIWifiDirectListener = new IWifiDirectListener() {
        @Override
        public void onCallP2pStateChanged(int state) {
            Dbug.i(tag, "-onCallP2pStateChanged- state : " + state);
        }

        @Override
        public void onCallP2pPeersChanged(List<WifiP2pDevice> peerList) {
            if(peerList != null && mApplication.getSearchMode() == IConstant.AP_SEARCH_MODE){
                Dbug.i(tag, "-onCallP2pPeersChanged- size : " + peerList.size());
                if(peerList.size() > 0){
                   WifiP2pDevice mConnectP2pDevice = null;
                    for (WifiP2pDevice device : peerList){
                        Dbug.i(tag, "-onCallP2pPeersChanged- device : " + device + ", isGroupOwner : "+device.isGroupOwner());
                        if((!device.isGroupOwner() && device.status != WifiP2pDevice.AVAILABLE) ||
                                (device.isGroupOwner() || device.status == WifiP2pDevice.CONNECTED)){
                            mConnectP2pDevice = device;
                            break;
                        }
                    }
                    if(mConnectP2pDevice != null){
                        String connectName = mConnectP2pDevice.deviceName;
                        if(!TextUtils.isEmpty(connectName) && connectName.startsWith(IConstant.WIFI_PREFIX)){
                            WifiP2pHelper.getInstance(getContext()).setConnectWifiDevice(mConnectP2pDevice);
                            if(ClientManager.getClient().isConnected()){
                                enterLiveVideo();
                            }else{
                                PreferencesHelper.putStringValue(mApplication, CURRENT_WIFI_SSID, connectName);
                                PreferencesHelper.putIntValue(mApplication, RECONNECT_TYPE, RECONNECT_TYPE_WIFI_DIRECT);
                                if(mApplication.isWifiDirectGO()){
                                    WifiP2pHelper.getInstance(getContext()).requestConnectionInfo();
                                }else{
                                    Dbug.e(tag, "It isn't WiFi direct go");
                                }
//                                ((MainActivity) getActivity()).connectDevice(IConstant.DEFAULT_DEV_IP);
                            }
                        }
                    }
                }
            }
        }

        @Override
        public void onCallP2pConnectionChanged(WifiP2pInfo wifiP2pInfo) {
            if(wifiP2pInfo != null){
                Dbug.i(tag, "-onCallP2pConnectionChanged- : " + wifiP2pInfo);
                if(mApplication.getSearchMode() == IConstant.DEV_AP_MODE
                        && mApplication.isWifiDirectGO() && wifiP2pInfo.groupFormed){
                    InetAddress groupOwnerAddress = wifiP2pInfo.groupOwnerAddress;
                    if(groupOwnerAddress != null){
                        if(ClientManager.getClient().isConnected()){
                            enterLiveVideo();
                        }else{
                            ((MainActivity) getActivity()).connectDevice(groupOwnerAddress.getHostAddress());
                        }
                    }
                }
            }
        }

        @Override
        public void onCallP2pDeviceChanged(WifiP2pDevice wifiP2pDevice) {
//            Dbug.i(tag, "-onCallP2pDeviceChanged- : " + wifiP2pDevice + "\n isGroupOwner : " +  wifiP2pDevice.isGroupOwner());
        }
    };

    private void enterWiFiSettings() {
        try {
            Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
            ComponentName componentName = intent.resolveActivity(getActivity().getPackageManager());
            if (componentName != null) {
                startActivity(intent);
            } else {
                ToastUtil.showToastLong(getString(R.string.go_to_wifi_settings));
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showToastLong(getString(R.string.go_to_wifi_settings));
        }
    }
}
